var imageryLayers;
var viewModel;
var toolbar;

function colorSettingOnload() {
    imageryLayers = viewer.imageryLayers;
    viewModel = {
        brightness: 0,
        contrast: 0,
        hue: 0,
        saturation: 0,
        gamma: 0
    };
    Cesium.knockout.track(viewModel);
    toolbar = document.getElementById('color_toolbar');
    Cesium.knockout.applyBindings(viewModel, toolbar);

    subscribeLayerParameter('brightness');
    subscribeLayerParameter('contrast');
    subscribeLayerParameter('hue');
    subscribeLayerParameter('saturation');
    subscribeLayerParameter('gamma');

    imageryLayers.layerAdded.addEventListener(updateViewModel);
    imageryLayers.layerRemoved.addEventListener(updateViewModel);
    imageryLayers.layerMoved.addEventListener(updateViewModel);
    updateViewModel();
}

function subscribeLayerParameter(name) {
    Cesium.knockout.getObservable(viewModel, name).subscribe(
        function(newValue) {
            if (imageryLayers.length > 0) {
                var layer = imageryLayers.get(1);
                layer[name] = newValue;
                var layer1 = imageryLayers.get(0);
                layer1[name] = newValue;
            }
        }
    );
}

function updateViewModel() {
    if (imageryLayers.length > 0) {
        var layer = imageryLayers.get(1);
        if (layer) {
            viewModel.brightness = layer.brightness;
            viewModel.contrast = layer.contrast;
            viewModel.hue = layer.hue;
            viewModel.saturation = layer.saturation;
            viewModel.gamma = layer.gamma;
        }
    }
}